前一篇我們瞭解 TestingModule 運作的方式,接下來介紹常見的 function test 情境。
今天課程是,有興趣的讀者可以上 Udemy 看看
先看看 Neil 準備的 component.ts 有哪些 function
從圖上可以看到幾點:
來看看 spec 怎麼寫,這邊我會把 it 的區塊列出來,describle 的區塊如圖:
line 13
: 宣告要測試的元件, 也就是 TestingFunctionsAreCalledUsingSpiesComponent
想到 function 測試,就用 spyOn 取得元件
接下來看看 it 有哪些:
it('should create', () => {
//Assign
//Act
//Assert
expect(component).toBeTruthy();
});
doSomething
是否 call loadData()
有回應doSomething
不該 call dontLoadData()
,在expect 要加 not
it('should call a function during another function', () => {
//Assign
const spy = spyOn(component,'doSomething');
//Act
component.loadData();
//Assert
expect(spy).toHaveBeenCalledWith();
});
it('should not call a function during another function', () => {
//Assign
const spy = spyOn(component,'doSomething');
//Act
component.dontLoadData();
//Assert
expect(spy).not.toHaveBeenCalledWith();
});
it('should call a function during another function without spy variable', () => {
//Assign
spyOn(component,'doSomething');
//Act
component.loadData();
//Assert
expect(component.doSomething).toHaveBeenCalledWith();
});
(4) 如果真的有需要測試 private function,就把 private function 名稱當作 key 執行私有函式
(5) 同樣也可以測試 private function 是否有 call 另一個函式
it('should call a function during a private function', () => {
//Assign
const spy = spyOn(component,'insidePrivateFunction');
//Act
component['privateFunction']();
//Assert
expect(spy).toHaveBeenCalledWith();
});
it('should call a private function during another function', () => {
//Assign
spyOn<any>(component,'privateFunction');
//Act
component.callPrivateFunction();
//Assert
expect(component['privateFunction']).toHaveBeenCalledWith();
});
(6) 測試 function 從 service 取資料,先 inject 用到的 service,再用 spyOn 取得 service 的 getData
it('should call a function on a service', () => {
//Assign
const apiService = TestBed.inject(ApiService);
spyOn(apiService,'getData');
//Act
component.serviceFunctionCalled();
//Assert
expect(apiService.getData).toHaveBeenCalledWith();
});
(7) 測試 function return value 的正向和反向
it('should try loading data and be successful', () => {
//Assign
spyOn(component,'shouldLoadData').and.returnValue(true);
spyOn(component,'loadData');
//Act
component.tryLoadData();
//Assert
expect(component.loadData).toHaveBeenCalledWith();
});
it('should try load data and be unsuccessful', () => {
//Assign
spyOn(component,'shouldLoadData').and.returnValue(false);
spyOn(component,'dontLoadData');
//Act
component.tryLoadData();
//Assert
expect(component.dontLoadData).toHaveBeenCalledWith();
});
認識 function 測試項目有哪些,以及如何撰寫這些測試項目,發現作者專注測試「單一項目」做的極致,有這些範例可以當作 pocket test item,如果日後測試 function 時如果忘記要測什麼,可以當作案例參考
下一篇,繼續介紹其他的 Typescript 案例